<?php

namespace App\Http\Controllers\Api;

use App\Http\Models\Medical;
use App\Http\Models\MemberDoctor;
use App\Models\InvitationCode;
use Carbon\Carbon;
use Dcat\Admin\Models\Administrator;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

/**
 * 病例库
 *
 * @Author hechengwei
 * @email chichiooo@sina.com
 * @DateTime 2022-03-09
 */
class MedicalController extends BaseController
{

    public function getList(Request $request)
    {
        $rules = [
            'keywords' => ['required'],
            'page' => ['required'],
            'limit' => ['required'],
        ];

        $message = [
            'keywords.required' => '请输入关键字',
            'page.required' => '页码不能为空',
            'limit.required' => '限制条数不能为空',
        ];

        $payload = $request->only('keywords', 'page', 'limit');

        $validator = Validator::make($payload, $rules, $message);

        // 验证格式
        if ($validator->fails()) {
            return fail_message($validator->errors()->first());
        }

        $model = new Medical();

        $list = $model->getMedicalByKeyWords((int) $payload['page'], (int) $payload['limit'], ['keywords' => $payload['keywords']], ['id', 'title', 'medical_history', 'author', 'created_at']);

        return success($list);
    }
    /**
     * 热门推荐
     *
     * @Author hechengwei
     * @email chichiooo@sina.com
     * @DateTime 2022-12-20
     * @return json
     */
    public function hotRecommend(Request $request)
    {
        $rules = [
            'page' => ['required'],
            'limit' => ['required'],
        ];

        $message = [
            'page.required' => '页码不能为空',
            'limit.required' => '限制条数不能为空',
        ];

        $payload = $request->only('page', 'limit');

        $validator = Validator::make($payload, $rules, $message);

        // 验证格式
        if ($validator->fails()) {
            return fail_message($validator->errors()->first());
        }

        $model = new Medical();

        $list = $model->getHotRecommend((int) $payload['page'], (int) $payload['limit'], ['id', 'title', 'author']);

        return success($list);
    }


    /**
     * 根据活动ID获取热门推荐
     *
     * @Author hechengwei
     * @email chichiooo@sina.com
     * @DateTime 2023-02-02
     * @return json
     */
    public function hotRecommendByActivity(Request $request)
    {
        $rules = [
            'page' => ['required'],
            'limit' => ['required'],
            'act_id' => ['required'],
        ];

        $message = [
            'page.required' => '页码不能为空',
            'limit.required' => '限制条数不能为空',
            'act_id.required' => '缺少参数活动ID',
        ];

        $payload = $request->only('page', 'limit', 'act_id');

        $validator = Validator::make($payload, $rules, $message);

        // 验证格式
        if ($validator->fails()) {
            return fail_message($validator->errors()->first());
        }

        $model = new Medical();
        $where['act_id'] = $payload['act_id'];
        $list = $model->getHotRecommendByActId($where, (int) $payload['page'], (int) $payload['limit'], ['id', 'title', 'author']);

        return success($list);
    }

    /**
     * 病例详情
     *
     * @Author hechengwei
     * @email chichiooo@sina.com
     * @DateTime 2022-12-20
     * @param Request $request
     * @return json
     */
    public function getDetail(Request $request)
    {
        $rules = [
            'id' => ['required'],
        ];

        $message = [
            'id.required' => 'id不能为空',
        ];

        $payload = $request->only('id');

        $validator = Validator::make($payload, $rules, $message);

        // 验证格式
        if ($validator->fails()) {
            return fail_message($validator->errors()->first());
        }

        $where['id'] = $payload['id'];
        $where['user_id'] = memberId();
        $detail = Medical::where($where)->first();
        return success($detail);
    }

    /**
     * 删除病例
     *
     * @Author hechengwei
     * @email chichiooo@sina.com
     * @DateTime 2022-03-10
     * @param Request $request
     * @return json
     */
    public function delMedical(Request $request)
    {
        $rules = [
            'id' => ['required'],
        ];

        $message = [
            'id.required' => 'id不能为空',
        ];

        $payload = $request->only('id');

        $validator = Validator::make($payload, $rules, $message);

        // 验证格式
        if ($validator->fails()) {
            return fail_message($validator->errors()->first());
        }

        $where['id'] = $payload['id'];

        $where['user_id'] = memberId();

        // $res = Medical::delOneSoft($where);
        $res = Medical::where($where)->delete();

        if ($res) {
            return success($res);
        } else {
            return fail_message('没有权限');
        }
    }

    /**
     * 添加修改病例
     *
     * @Author hechengwei
     * @email chichiooo@sina.com
     * @DateTime 2024-06-24
     * @param Request $request
     * @return json
     */
    public function createMedical(Request $request)
    {
        // 邀请码
        $payload = $request->only([
            'id',
            'act_id',
            'name',
            'height',
            'weight',
            'sex',
            'age',
            'source',
            'source_input',
            'bim',
            'bim_radio',
            'symptom',
            'symptom_input',
            'disease_code',
            'course_disease',
            'drink_alcohol',
            'drink_alcohol_quantity',
            'drink_alcohol_frequency',
            'smoking_history',
            'smoking_history_year',
            'smoking_history_quantity',
            'family_historyL',
            'past_historyL',
            'medical_history',
            'allergy',
            'allergy_input',
            'check',
            'check_true',
            'check_true_laboratory',
            'check_true_image',
            'check_true_pathology',
            'check_true_other',
            'check_false',
            'check_false_input',
            'treatment',
            'treatment_plan_date',
            'treatment_specific',
            'treatment_effect',
            'treatment_return_visit',
            'treatment_untreated',
            'digestive_diseases',
            'digestive_diseases_laboratory',
            'digestive_diseases_image',
            'digestive_diseases_pathology',
            'digestive_diseases_other',
            'helicobacter_pylori',
            'comorbidities',
            'comorbidities_anxiety',
            'comorbidities_depression',
            'comorbidities_other',
            'disease_identify',
            'disease_identify_true',
            'disease_identify_false',
            'disease_diagnosis',
            'disease_diagnosis_input',
            'disease_classification',
            'disease_comorbidities',
            'disease_comorbidities_input',
            'treatment_plan',
            'treatment_date',
            'treatment_mg',
            'treatment_bag',
            'treatment_situation',
            'treatment_situation_input',
            'treatment_dose',
            'treatment_dose_input',
            'gastritis_clinical',
            'gastritis_laboratory',
            'gastritis_curativeeffect',
            'gastritis_complications',
            'ulcer_clinical',
            'ulcer_evaluation',
            'ulcer_hp',
            'ulcer_complications',
            'dyspepsia_evaluation',
            'dyspepsia_evaluate',
            'dyspepsia_quality',
            'ulcer_other',
            'otherdiseases_clinical',
            'otherdiseases_other',
            'adversereaction',
            'adversereaction_group',
            'adversereaction_group_input',
            'adversereaction_date',
            'adversereaction_immediately',
            'adversereaction_time_input',
            'adversereaction_degree',
            'adversereaction_related',
            'adversereaction_strategy',

            'tcm_syndrome_type',

            'pre_degree_pain_chest_ribs',
            'pre_degree_epigastric_full',
            'pre_degree_be_upset',
            'pre_degree_eructation_frequent',
            'pre_degree_mild_breathing',

            'pre_frequency_pain_chest_ribs',
            'pre_frequency_epigastric_full',
            'pre_frequency_be_upset',
            'pre_frequency_eructation_frequent',
            'pre_frequency_mild_breathing',

            'post_degree_pain_chest_ribs',
            'post_degree_epigastric_full',
            'post_degree_be_upset',
            'post_degree_eructation_frequent',
            'post_degree_mild_breathing',

            'post_frequency_pain_chest_ribs',
            'post_frequency_epigastric_full',
            'post_frequency_be_upset',
            'post_frequency_eructation_frequent',
            'post_frequency_mild_breathing',

            'invitation_code' // 邀请码
        ]);

        // $payload['symptom'] = ["1", "2", "3"];
        // dd(implode(',', $payload['symptom']));
        // 处理提交数组数据转成字符串
        $payload['symptom'] = isset($payload['symptom']) && !empty($payload['symptom']) ? implode(',', $payload['symptom']) : '';
        $payload['check_true'] = isset($payload['check_true']) && !empty($payload['check_true']) ? implode(',', $payload['check_true']) : '';
        $payload['check_false'] = isset($payload['check_false']) && !empty($payload['check_false']) ? implode(',', $payload['check_false']) : '';
        $payload['digestive_diseases']  = isset($payload['digestive_diseases']) && !empty($payload['digestive_diseases']) ? implode(',', $payload['digestive_diseases']) : '';
        $payload['comorbidities'] = isset($payload['comorbidities']) && !empty($payload['comorbidities']) ? implode(',', $payload['comorbidities']) : '';
        $payload['disease_diagnosis'] = isset($payload['disease_diagnosis']) && !empty($payload['disease_diagnosis']) ? implode(',', $payload['disease_diagnosis']) : '';
        $payload['adversereaction_group'] = isset($payload['adversereaction_group']) && !empty($payload['adversereaction_group']) ? implode(',', $payload['adversereaction_group']) : '';
        $payload['tcm_syndrome_type'] = isset($payload['tcm_syndrome_type']) && !empty($payload['tcm_syndrome_type']) ? implode(',', $payload['tcm_syndrome_type']) : '';

        $member = member();

        $payload['user_id'] = $member->userid;

        $id = $payload['id'];
        $invitation_code = isset($payload['invitation_code']) && !empty($payload['invitation_code']) ? $payload['invitation_code'] : '';

        unset($payload['id'], $payload['invitation_code']);
        if (isset($id) && $id != '') {
            $result = Medical::updateMedical($payload, $id);
            if ($result) {
                return success(['id' => $id]);
            } else {
                return fail_message();
            }
        } else {
            foreach ($payload as $key => &$val) {
                if (empty($val)) {
                    $val = '';
                }
            }
            $result = Medical::create($payload);
            if ($result) {
                $invitation = new InvitationCode();
                $invitation->useInvitationCode($invitation_code, $id);
                return success(['id' => $result->id]);
            } else {
                return fail_message();
            }
        }
    }

    /**
     * 检查邀请码
     *
     * @Author hechengwei
     * @email chichiooo@sina.com
     * @DateTime 2024-06-24
     * @param Request $request
     * @return void
     */
    public function checkCode(Request $request)
    {
        $rules = [
            'code' => ['required'],
        ];

        $message = [
            'code.required' => '请填写邀请码',
        ];

        $payload = $request->only('code');

        $validator = Validator::make($payload, $rules, $message);

        // 验证格式
        if ($validator->fails()) {
            return fail_message($validator->errors()->first());
        }

        $invitation = new InvitationCode();
        $invitation->checkInvitationCode($payload['code'], '', 'create');
        return success();
    }
}
